package cn.ii8080.i8.server.auth.web.config;

import cn.ii8080.i8.module.account.client.AccountClient;
import cn.ii8080.i8.module.account.vo.AccountVo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityBean {
    private final AccountClient accountClient;

    public WebSecurityBean(AccountClient accountClient) {
        this.accountClient = accountClient;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            AccountVo account = accountClient.getOne(AccountClient.ACCOUNT_COLUMN, username);
            if (account == null) {
                return null;
            }
            User user = new User(account.getAccount(), account.getPassword(), account.getEnabled(), true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));
            return user;
        };
    }
}
